//
//  IAPTMP.swift
//  Source_iOS
//
//  Created by Toj on 5/10/22.
//

import Foundation
/*
// 1.首先集成导入支付包
// 集成: General -> Frameworks -> + StoreKit
// 导入
import StoreKit

open class IAPManager: NSObject {
    
    static let manager = IAPManager()
    
    // public var payState: IAPPurchaseState = .cancel
    
    private var completeHandle: IAPCompletionHandle? = nil
    
    private override init() {
        super.init()
        
        // 2. 初始化内购支付服务
        SKPaymentQueue.default().add(self)
    }
    
    // 3. 判断app是否允许apple支付
    func requestProduct(_ productID: String, complete: @escaping IAPCompletionHandle) {
        let canPayments = SKPaymentQueue.canMakePayments()
        guard canPayments else {
            print("-->toj: 苹果现在不能支付, 请稍后再试")
            completeHandle?(.notArrow, nil)
            return
        }
        
        completeHandle = complete
        requestAppleProduct(productID)
    }
    
    private var selectedProductID = ""
    // 4. 请求苹果后台商品
    private func requestAppleProduct(_ productID: String) {
        
        selectedProductID = productID
        var products: Set<String> = []
        products.insert(productID)
        // 初始化请求
        let request = SKProductsRequest(productIdentifiers: products)
        request.delegate = self;
        // 开始请求
        request.start()
    }
}

extension IAPManager: SKProductsRequestDelegate {
    
    // 5. 接收到产品的返回信息,然后用返回的商品信息进行发起购买请求
    public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        let products = response.products
        guard products.count > 0 else {
            // 理论上不存在
            print("-->toj: 服务器没有产品")
            completeHandle?(.notExist, nil)
            return
        }
        
        // 选择的产品
        var requestProduct: SKProduct? = nil
        
        // 5.1 遍历产品从中找到选择的产品
        for product in products {
            print("-->toj: description: \(product.description)")
            print("-->toj: localizedTitle: \(product.localizedTitle)")
            print("-->toj: localizedDescription: \(product.localizedDescription)")
            print("-->toj: price: \(product.price)")
            print("-->toj: productIdentifier: \(product.productIdentifier)")
            
            if selectedProductID != product.productIdentifier { continue }
            
            requestProduct = product
            break
        }
        
        guard let product = requestProduct else {
            // 理论上不存在
            print("-->toj: 没有找到选择的产品")
            completeHandle?(.unfound, nil)
            return
        }
        
        // 5.2 发送购买请求
        let payment = SKPayment(product: product)
        // 添加到购买队列
        SKPaymentQueue.default().add(payment)
    }
    
    // 请求失败
    public func request(_ request: SKRequest, didFailWithError error: Error) {
        print("-->toj: 从App Store中检索关于指定产品列表的本地化信息错误 error:%@", error)
        completeHandle?(.failed, nil)
    }
    
    // 反馈请求的产品信息结束后
    public func requestDidFinish(_ request: SKRequest) {
        print("-->toj: requestDidFinish")
        completeHandle?(.finish, nil)
    }
}

extension IAPManager: SKPaymentTransactionObserver {
    // 6. 监听购买结果
    public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        for transaction in transactions {
            switch (transaction.transactionState) {
            case .purchased:
                print("-->toj: 交易完成")
                break;
            case .purchasing:
                print("-->toj: 商品添加进列表")
                break;
            case .restored:
                print("-->toj: 已经购买过商品")
                SKPaymentQueue.default().finishTransaction(transaction)
                break;
            case .failed:
                print("-->toj: 交易失败")
                SKPaymentQueue.default().finishTransaction(transaction)
                break;
            default:
                break;
            }
        }
    }
}

extension IAPManager {
    // 7. 验证支付信息
    // 当交易结束后还要去appstore上验证支付信息是否都正确,只有所有都正确后,我们就可以给用户方法我们的虚拟物品了.
    func completeTransaction(transaction: SKPaymentTransaction) {
        guard let url = Bundle.main.appStoreReceiptURL else {
            print("-->toj: 苹果没有返回交易凭证")
            return
        }
        
        guard let _ = NSData(contentsOf: url) else {
            print("-->toj: 本地没有找到交易凭证")
            return
        }
        // 把当前的凭证信息不用app端验证,
        // 发送给我们服务器, 让服务器验证凭证的真实性, 返回给我们最后的验证结果
    }
}
*/
